package com.snap.vseries.ui;

import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.snap.vseries.R;
import com.snap.vseries.adapter.TemplateAdapter;
import com.snap.vseries.base.BaseActivity;
import com.snap.vseries.bean.ExpEntity;
import com.snap.vseries.model.DBManager;
import com.snap.vseries.utils.TopTitleUtils;

import org.litepal.crud.callback.FindMultiCallback;

import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * 本地项目管理：
 * 1、从本地移除
 * 2、排序
 * 3、添加远程项目到本地
 *
 * @author Rachel
 */
public class TemplatesManagerActivity extends BaseActivity {


    @BindView(R.id.container)
    RecyclerView container;
    private TemplateAdapter templateAdapter;
    private List<ExpEntity> datas;
    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            int dragFlag = 0;
            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            } else if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                dragFlag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            }
            return makeMovementFlags(dragFlag, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            int fromPosition = viewHolder.getAdapterPosition();
            int toPosition = target.getAdapterPosition();
            if (fromPosition < toPosition) {
                for (int i = fromPosition; i < toPosition; i++) {
                    Collections.swap(datas, i, i + 1);
                }
            } else {
                for (int i = fromPosition; i > toPosition; i--) {
                    Collections.swap(datas, i, i - 1);
                }
            }
            templateAdapter.notifyItemMoved(fromPosition, toPosition);
            for (int i = 0; i < datas.size(); i++) {
                datas.get(i).setSortId(i);
            }
            DBManager.get().saveTemplateList(datas);
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

        }

        /**
         *  By default, ItemTouchHelper starts a drag when a View is long pressed.
         *  You can disable that behavior by overriding ItemTouchHelper.Callback#isLongPressDragEnabled().
         *  默认情况下，长按view时，ItemTouchHelper开始拖动
         *  你可以通过重写isLongPressDragEnabled这个方法来禁用这个行为
         */
        @Override
        public boolean isLongPressDragEnabled() {
            return false;
        }

        /**
         * 长按选中Item的时候开始调用
         * 长按高亮
         */
        @Override
        public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
            if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                viewHolder.itemView.setBackgroundColor(Color.WHITE);
                //获取系统震动服务//震动70毫秒
                Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vib.vibrate(70);
            }
            super.onSelectedChanged(viewHolder, actionState);
        }

        /**
         * 手指松开的时候还原高亮
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            super.clearView(recyclerView, viewHolder);
            viewHolder.itemView.setBackgroundColor(0);
            templateAdapter.notifyDataSetChanged();
        }
    });

    @Override
    protected int layoutResId() {
        return R.layout.activity_templates_manager;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }

    private void initData() {

    }

    private void initView() {
        ImageView imageView = new ImageView(this);
        imageView.setBackground(this.getResources().getDrawable(R.drawable.ic_add_template));
        new TopTitleUtils(this).setTitle("检测项目管理").addRightView(imageView)
                .setRightViewVisiable(View.VISIBLE)
                .setRight(v -> {
                    Intent intent = new Intent(this, TemplatesAddActivity.class);
                    startActivity(intent);
                });
        templateAdapter = new TemplateAdapter(this, null, helper);
        container.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        container.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
        container.setAdapter(templateAdapter);
        notifyTemplateList();

    }

    private void notifyTemplateList() {
        DBManager.get().getTemplateList(new FindMultiCallback<ExpEntity>() {
            @Override
            public void onFinish(List<ExpEntity> list) {
                templateAdapter.updateData(list);
                datas = list;
                helper.attachToRecyclerView(container);
            }
        });
    }
}
